package cn.caishen.report.common.exceptions;

import cn.caishen.report.common.utils.LbMap;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ResponseResult {

    public static Integer SUCCESS_CODE = 0;
    public static Integer FAIL_CODE = 1;
    public static Integer LOGIN_FAIL_CODE = 2;

    public static LbMap success(String msg) {
        LbMap resultMap = new LbMap();
        resultMap.put("result", true);
        resultMap.put("code", SUCCESS_CODE);
        resultMap.put("msg", msg);
        resultMap.put("data", null);
        resultMap.put("count", 0);
        return resultMap;
    }

    public static LbMap success(String msg, Object o, Long count) {
        LbMap resultMap = new LbMap();
        resultMap.put("result", true);
        resultMap.put("code", SUCCESS_CODE);
        resultMap.put("msg", msg);
        resultMap.put("data", o);
        resultMap.put("count", count);
        return resultMap;
    }

    public static LbMap success(String msg, Object o) {
        LbMap resultMap = new LbMap();
        resultMap.put("result", true);
        resultMap.put("code", SUCCESS_CODE);
        resultMap.put("msg", msg);
        resultMap.put("data", o);
        resultMap.put("count", 0);
        return resultMap;
    }

    public static LbMap success(String msg, Object o, Integer count) {
        LbMap resultMap = new LbMap();
        resultMap.put("result", true);
        resultMap.put("code", SUCCESS_CODE);
        resultMap.put("msg", msg);
        resultMap.put("data", o);
        resultMap.put("count", count);
        return resultMap;
    }

    public static LbMap fail(String msg) {
        return fail(msg, FAIL_CODE, "");
    }

    public static LbMap fail(String msg, String requestUrl) {
        return fail(msg, FAIL_CODE, requestUrl);
    }

    public static LbMap fail(String msg, Integer code) {
        return fail(msg, code, "");
    }

    public static LbMap fail(String msg, Integer code, String requestUrl) {
        LbMap resultMap = new LbMap();
        resultMap.put("result", false);
        resultMap.put("code", code);
        resultMap.put("msg", msg);
        resultMap.put("requestUrl", requestUrl);

        Throwable t = new Throwable();
        StackTraceElement[] stackTraceElements = t.getStackTrace();

        String fileName = "";
        String methodName = "";

        //查找调用过来的类或者方法
        for (StackTraceElement stackTraceElement : stackTraceElements) {
            if (stackTraceElement.getClassName().contains("cn.caishen") &&
                    stackTraceElement.getClassName().contains("controller")) {
                fileName = stackTraceElement.getFileName();
                methodName = stackTraceElement.getMethodName();
                break;
            }
        }
        log.info("ResponseResult failed from path:[{}], method:[{}], error message:[{}]", fileName, methodName, msg);

        return resultMap;
    }
}
